<script setup>
import EditContainer from "@/components/AdminConponents/EditContainer.vue";
import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {useRoute, useRouter} from "vue-router";
import {ref, watch} from "vue";
import {newsGetAPI, newsUpdateAPI} from "@/api/AdminApi/news.js";
import {ElMessage} from "element-plus";
import {publisherGetAllAPI} from "@/api/AdminApi/publisher.js";
import {gameGetByPublisherIdAPI} from "@/api/AdminApi/game.js";

const route = useRoute()
const newsInfo = ref({
  publisher: {},
  game: {}
})

const getNewsInfo = async (id = route.params.id) => {
  const res = await newsGetAPI(id)
  newsInfo.value = res.data
}
getNewsInfo()

// 定义工具栏选项
const toolbarOptions = {
  container: [
    ['bold', 'italic', 'underline'],  // 加粗、斜体、下划线按钮
    [{'header': 1}, {'header': 2}],  // 标题1、标题2
    ['image']  // 插入图片按钮
  ]
}

// 取消按钮
const router = useRouter()
const cancel = () => {
  router.go(-1)
}

const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ]
}

const formRef = ref()
// 修改按钮
const edit = async (type) => {
  await formRef.value.validate()
  if (newsInfo.value.content === null) {
    ElMessage.error("新闻内容不能为空！")
    return
  }
  if (newsInfo.value.publisher.id === null) {
    ElMessage.error("发行商不能为空！")
    return
  }
  newsInfo.value.type = type
  const {publisher, game, ...newsDTO} = newsInfo.value
  const requestPayload = {
    publisherId: publisher.id,
    ...(game && { gameId: game.id }), // 仅当game不为null时添加gameId
    ...newsDTO
  };
  const res = await newsUpdateAPI(requestPayload)
  if (res.code === 1) {
    ElMessage.success("更新成功")
    router.go(-1)
  } else {
    ElMessage.error(res.msg)
  }
}

/**
 * 发行商对话框
 */
const AllPublishers= ref([])
const dialogVisible1 = ref(false)
const publisherName = ref()
// 打开分类列表
const showAllPublishers = () => {
  dialogVisible1.value = true
}

const timer1 = ref()
watch(publisherName, (newValue) => {
  AllPublishers.value = []
  clearTimeout(timer1.value)
  timer1.value = setTimeout(async () => {
    const res = await publisherGetAllAPI(newValue)
    AllPublishers.value = res.data
  }, 300);
}, { deep: true, immediate: true });

const selectPublisher = (item) => {
  newsInfo.value.publisher = item
  dialogVisible1.value = false
}

const AllGames= ref([])
const dialogVisible2 = ref(false)

// 打开分类列表
const showAllGames = async () => {
  if (newsInfo.value.publisher.id === null) {
    ElMessage.error("请求先选择发行商")
    return
  }
  dialogVisible2.value = true
  const res = await gameGetByPublisherIdAPI(newsInfo.value.publisher.id)
  AllGames.value = res.data
}

const selectGame = (item) => {
  newsInfo.value.game = item
  dialogVisible2.value = false
}
</script>

<template>
  <EditContainer title="新闻编辑">
    <template #body>
      <el-form ref="formRef" :model="newsInfo" :rules="rules" label-width="auto" style="max-width: 1200px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsInfo.title"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="type">
          {{newsInfo.type === 0 ? '草稿' : '已发布'}}
        </el-form-item>
        <el-form-item label="发行商" prop="publisher">
          {{ newsInfo.publisher.name }}
          <el-button style="margin-left: 30px" type="success" @click="showAllPublishers">
            + 关联发行商
          </el-button>
        </el-form-item>
        <el-form-item label="关联游戏" prop="game">
          {{ newsInfo.game !== null ? newsInfo.game.chineseName : "无" }}
          <el-button style="margin-left: 30px" type="success" @click="showAllGames">
            + 关联游戏
          </el-button>
        </el-form-item>
        <el-form-item label="内容">
          <div class="editor">
            <quill-editor
                ref="editorRef"
                v-model:content="newsInfo.content"
                content-type="html"
                theme="snow"
                :toolbar="toolbarOptions"
            >
            </quill-editor>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template #footerLeft>
      <el-button class="button" @click="cancel" type="info">取消</el-button>
    </template>
    <template #footerRight>
      <el-button class="button" @click="edit(0)" type="primary">存草稿</el-button>
      <el-button class="button" @click="edit(1)" type="primary">发布</el-button>
    </template>
  </EditContainer>
  <el-dialog
      width="500px"
      draggable
      v-model="dialogVisible1">
    <span>发行商名称:&nbsp;&nbsp;</span>
    <el-input v-model="publisherName" style="width: 240px" placeholder="请输入发行商名称" />
    <el-scrollbar class="scrollbarContainer" height="300px">
      <div class="publisherItem" v-for="item in AllPublishers" :key="item" @click="selectPublisher(item)">
        <div class="layoutItem">
          <div class="left">
            <el-image :src="item.icon"></el-image>
          </div>
          <div class="right">
            <div class="ellipsis" style="width: 148px;"><strong>{{item.name}}</strong></div>
            <div style="font-size: 12px; margin-top: 4px">成立日期：</div>
            <div>{{item.createDate}}</div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </el-dialog>
  <el-dialog
      width="500px"
      draggable
      v-model="dialogVisible2">
    <span>{{newsInfo.publisher.name}}的游戏:&nbsp;&nbsp;</span>
    <el-scrollbar class="scrollbarContainer" height="300px">
      <div class="gameItem" v-for="item in AllGames" :key="item" @click="selectGame(item)">
        <div class="layoutItem">
          <div class="left">
          </div>
          <div class="right">
            <div class="ellipsis" style="width: 200px;"><strong>{{item.chineseName}}({{item.englishName}})</strong></div>
            <div style="font-size: 12px; margin-top: 4px">发布日期：</div>
            <div>{{item.issueDate}}</div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </el-dialog>
</template>

<style scoped>
.editor {
  width: 100%;
  height: 800px;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.scrollbarContainer {
  margin-top: 10px;
  display: flex;
  .publisherItem {
    display: inline-block;
    height: 80px;
    width: 234px;
    padding: 5px;
    cursor: pointer;
    .layoutItem {
      display: flex;
      .left {
        width: 70px;
        height: 70px;
      }
      .right {
        margin-left: 5px;
        height: 70px;
      }
    }
  }
  .publisherItem:hover {
    background-color: #d7d7d7;
  }
  .gameItem {
    display: inline-block;
    height: 80px;
    width: 234px;
    padding: 5px;
    cursor: pointer;
    .layoutItem {
      display: flex;
      .right {
        margin-left: 5px;
        height: 70px;
      }
    }
  }
  .gameItem:hover {
    background-color: #d7d7d7;
  }
}
</style>
